import {createStore} from 'vuex'
import {toArrayTree} from 'xe-utils'
import {Init} from "@js/api/Common";

export default createStore({
	state: {
		isGroup: false,
		siderCollapsed: false,
		user: {},
		organization: {},
		checkout: {},
		menus: [],
		granted:[],
	},
	mutations: {
		updateMenus(state, data) {
			state.menus = data;
		},
		updateAccount(state, {organization, account}) {
			state.user = account;
			state.isGroup = account.group;
			state.organization = organization;
			state.checkout = account.checkout;
			state.granted = account.granted || [];
		},
		updateCheckout(state, checkout) {
			state.checkout = checkout;
		},
		updateSiderCollapse(state, isShow) {
			setTimeout(() => {
				state.pageResizeCount += 1;
			}, 600);
			state.siderCollapsed = isShow;
		}
	},
	actions: {
		init({commit}) {
			return new Promise((resolve, reject) => {
				Init().then(({success, data}) => {
					if (success) {
						commit('updateAccount', data);
						commit('updateMenus', toArrayTree(data.menus.filter(val => val.group === (data.account.group ? 'MERCHANT' : 'STORE')), {strict: true}));
						resolve(data.account);
					} else {
						reject();
					}
				}).catch(() => {
					reject();
				})
			})
		},
		updateSiderCollapse({commit}, data) {
			commit('updateSiderCollapse', data);
		}
	},
	getters: {
		account: state => {
			return state.user;
		},
		checkout: state => {
			return state.checkout;
		},
		siderCollapsed: state => {
			return state.siderCollapsed;
		}
	}
})
